#!/bin/sh

config=/etc/psa/psa.conf

work_dir=`pwd`

product_root=`grep PRODUCT_ROOT_D "$config" | grep -v '^#' | awk '{print $2}'`
if [ -z "$product_root" ]; then
	echo "ERROR: Unable to define $product root directory."
	exit 1
fi

echo -n "Detecting default locale ... "
def_locale=`cat $product_root/admin/htdocs/locales/default | cut -d ':' -f 1`
if [ ! -z "$def_locale" ]; then
	echo -e "done.\n\"$def_locale\" is detected as default locale, it will be used as original locale."
else
	def_locale="en-US"
	echo "Can't detect default locale, en-US will be used as original locale."
fi


echo -n "Preparing original locale (in ./orig_locale.$def_locale) ... "
rm -rf ./orig_locale.$def_locale \
&& mkdir -p ./orig_locale.$def_locale \
&& mkdir -p ./orig_locale.$def_locale/htdocs/locales \
&& mkdir -p ./orig_locale.$def_locale/plib/locales \
|| exit 1

### check for iconv, error about non-existent iconv tool appears later because of iconv is required only if html is not in uft-8 enconding.
iconv="`which iconv`"

### copy (convert if it isn't in utf8) source locale
for dirs in $product_root/admin/plib/locales/$def_locale:$work_dir/orig_locale.$def_locale/plib/locales/ $product_root/admin/htdocs/locales/$def_locale:$work_dir/orig_locale.$def_locale/htdocs/locales/; do
	src_dir=`echo "$dirs" | cut -d ':' -f 1`
	dst_dir=`echo "$dirs" | cut -d ':' -f 2`

	#echo "($src_dir)($dst_dir)"

	cd $src_dir || exit 1

	find ./ -type f | while read file; do
		### create dst dir
		dir=`echo $file | sed -e 's/^\(.*\)\/[^\/]*$/\1/'`
		mkdir -p "$dst_dir/$dir"

		### check for html file
		echo "$file" | grep '\.html*\?$' >/dev/null
		if [ 0$? -eq 0 ]; then ### it is html file
			### check that charset is utf-8
			grep -i 'charset=utf-*8' $file >/dev/null
			if [ 0$? -ne 0 ]; then ### charset isn't utf-8
				if [ -z "$iconv" ]; then
					echo -e "\nHTML files of the source LP are not in UTF-8 charset. Install the iconv tool to your system, and then rerun this utility to get valid source LP files."
					rm -rf $work_dir/orig_locale.$def_locale >/dev/null
					exit 1
				fi
				### convert html file to utf-8
				$iconv -f cp1252 -t utf-8 $file | sed -e 's/charset=[A-Za-z0-9-]*[A-Za-z0-9]/charset=UTF-8/g' > "$dst_dir/$file" || exit 1
			else
				### simply copy if a html file already is in utf-8 encoding
				cp -f $file "$dst_dir/$file" || exit 1
			fi
		else
			### simply copy if it isn't a html file
			cp -f $file "$dst_dir/$file" || exit 1
		fi
	done
done

cd $work_dir
echo done
